<template>
  <el-container class="home-container">
    <el-header><!-- 头部区 -->
      <div>
        <span id="fontLogo">智能快递柜后台管理系统</span>
      </div>
      <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
          id="indexMenu">
        <el-menu-item index="1">首页</el-menu-item>
        <!--        点击事件跳转会员列表界面-->
        <el-menu-item index="2" @click="expressList">会员</el-menu-item>
        <el-menu-item index="3" @click="goToMachine">柜机</el-menu-item>
        <el-menu-item index="4" @click="baoguo">包裹</el-menu-item>
        <el-menu-item index="5" @click="tiaozhuan">财务</el-menu-item>
        <el-menu-item index="6" @click="other">其他</el-menu-item>
      </el-menu>
      <div>
        <el-dropdown trigger="click" @command="handleCommand">
          <span id="fontName">
            {{ this.name }}
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">账号设置</el-dropdown-item>
            <el-dropdown-item command="b">修改密码</el-dropdown-item>
            <el-dropdown-item command="c">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!--        <span id="fontName">{{ this.name }}</span>-->
      </div>
    </el-header>
    <!-- 页面主体区域 -->
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="210px" hight="100%">
        <el-menu
            class="el-menu-vertical-demo"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b">
          <el-menu-item index="1">
            <i class="el-icon-menu"></i>
            <span slot="title">系统首页</span>
          </el-menu-item>
          <el-menu-item index="2" @click="expressList">
            <i class="el-icon-menu"></i>
            <span slot="title">会员管理</span>
          </el-menu-item>
          <el-menu-item index="3" @click="goToMachine()">
            <i class="el-icon-menu"></i>
            <span slot="title">柜机管理</span>
          </el-menu-item>
          <el-menu-item index="4" @click="baoguo">
            <i class="el-icon-menu"></i>
            <span slot="title">包裹管理</span>
          </el-menu-item>
          <el-menu-item index="5" disabled>
            <i class="el-icon-menu"></i>
            <span slot="title">活动管理</span>
          </el-menu-item>
          <el-menu-item index="6" @click="tiaozhuan()">
            <i class="el-icon-menu"></i>
            <span slot="title">财务管理</span>
          </el-menu-item>
          <el-menu-item index="7" @click="other">
            <i class="el-icon-menu"></i>
            <span slot="title">其他设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <!-- 右侧内容主体 -->
      <el-main>
        <!--寄派件数据-->
        <el-row :gutter="20">
          <el-col :span="4">
            <div id="indexOne" style="background-color: #6081e2">
              <span id="indexOneFont">今日派件量</span><br>
              <span id="indexOneNumber">
                {{ this.deliveryDay.num != null ? this.deliveryDay.num : 0 }}
              </span>
            </div>
          </el-col>
          <el-col :span="4">
            <div id="indexOne" style="background-color: #44bdd0">
              <span id="indexOneFont">今日寄件量</span><br>
              <span id="indexOneNumber">
                {{ this.sendDay.num != null ? this.sendDay.num : 0 }}
              </span>
            </div>
          </el-col>
          <el-col :span="4">
            <div id="indexOne" style="background-color: #e85b4e">
              <span id="indexOneFont">今日派件收入</span><br>
              <span id="indexOneNumber">
                {{ this.deliveryDay.profit != null ? this.deliveryDay.profit : 0 }}
              </span>
            </div>
          </el-col>
          <el-col :span="4">
            <div id="indexOne" style="background-color: #33cd95">
              <span id="indexOneFont">今日寄件收入</span><br>
              <span id="indexOneNumber">
                {{ this.sendDay.profit != null ? this.sendDay.profit : 0 }}
              </span>
            </div>
          </el-col>
          <el-col :span="4">
            <div id="indexOne" style="background-color: #fea013">
              <span id="indexOneFont">今日总收入</span><br>
              <span id="indexOneNumber">
                {{
                  (this.sendDay.profit != null ? parseInt(this.sendDay.profit) : 0)
                  +
                  (this.deliveryDay.profit != null ? parseInt(this.deliveryDay.profit) : 0)
                }}
              </span>
            </div>
          </el-col>
        </el-row>
        <!--寄派件数据折线图和每日开箱数-->
        <el-row style="margin-top: 10px">
          <el-col :span="15">
            <div id="indexTwoLeft">
              <span style="font-size: 14px">
                <b>派件量与寄件量趋势图</b>
              </span>
              <div>
                <canvas id="myLineChart" width="200" height="100"></canvas>
              </div>
            </div>
          </el-col>
          <el-col :span="7">
            <div id="indexTwoRight">
              <span style="font-size: 14px">
                <b>当前时间:</b> {{ formattedDate }} {{ currentDay }} {{ currentTime }}
              </span>
              <div id="indexTwoRightBottom">
                <div id="indexTwoRightYuan">
                  <p style="font-size: 45px;color: #ff7733">{{ newNumber }}</p>
                  <p>今日开箱数</p>
                </div>
                <p style="margin-top: 30px;font-size: 12px;color: #8c939d">每隔一分钟更新一次数据</p>
              </div>
            </div>
          </el-col>
        </el-row>
        <!--会员状况环状图-->
        <el-row style="margin-top: 10px">
          <el-col :span="10">
            <div id="indexThreeLeft">
              <p style="font-size: 14px"><b>会员状况</b></p>
              <div style="width: 130px;float: left">
                <p style="font-size: 16px;color: #ff7733;line-height: 80px;">
                  当前<font size="6">{{ member.nums }}</font>会员
                </p>
                <p style="font-size: 16px;line-height: 50px">
                  累计<font size="6">{{ member.vipNum }}</font>快递员
                </p>
                <p style="font-size: 16px;line-height: 50px">
                  累计<font size="6">{{ member.courierNum }}</font>普通会员
                </p>
              </div>
              <div style="width: 300px;float: right">
                <canvas id="myDoughnutChart"></canvas>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div id="indexThreeRight">
              <div style="width: 150px;float: left;margin-top: 48px">
                <p style="font-size: 16px;color: #ff7733;line-height: 80px;">
                  昨日新增<font size="6">{{ addMember.nums }}</font>会员
                </p>
                <p style="font-size: 16px;line-height: 50px">
                  昨日新增<font size="6">{{ addMember.courierNum }}</font>快递员
                </p>
                <p style="font-size: 16px;line-height: 50px">
                  昨日新增<font size="6">{{ addMember.vipNum }}</font>普通会员
                </p>
              </div>
              <div style="width: 300px;float: right;margin-top: 48px">
                <canvas id="myDoughnutAddChart"></canvas>
              </div>
            </div>
          </el-col>
        </el-row>
        <!--柜机数据显示-->
        <el-row style="margin-top: 10px">
          <el-col :span="14">
            <div id="indexFourLeft">
              <p style="font-size: 14px"><b>柜机状况</b></p>
              <div id="mapDiv">
                <MyMapChart :width="'600px'" :height="'450px'"/>
              </div>
            </div>
          </el-col>
          <el-col :span="10">
            <div id="indexFourRight">
              <canvas id="mapDataChart" width="200" height="100"></canvas>
            </div>
            <el-button type="primary" style="width: 100%;margin-top: 10px" @click="openMap">
              查看柜机分布地图
            </el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import {getNewOpenNum, getMapChart} from "@/api/machine/VendingMachine"

import axios from "axios";
import {Message} from "element-ui";
import {Chart, registerables} from 'chart.js';
import moment from "moment/moment";
import MyMapChart from '@/views/MyMapChart.vue';

Chart.register(...registerables); // 注册所有的组件

export default {
  components: {
    MyMapChart
  },
  data() {
    return {
      activeIndex: '1',
      name: sessionStorage.getItem("name"),
      formattedDate: '',// 用于存储当前日期
      currentTime: '', // 用于存储当前时间
      currentDay: '', // 用于存储当前星期几
      myTimeDisplay: null, // 定时器
      sendDay: {},//当前寄件数据
      deliveryDay: {},//当前派件数据
      sendLineChart: [],//寄件折线图数据
      deliveryLineChart: [],//派件折线图数据
      chart: null,//折线图对象
      memberChart: null,//会员环状图对象
      addMemberChart: null,//新增会员环状图对象
      mapDataChart: null,//地图数据对象
      newNumber: 0,//新开柜机数量
      member: {},//会员数据
      addMember: {},//新增会员数据
      mapData: []//地图数据
    };
  },
  created() {
    // getUser().then(res => {
    //   console.log(res);
    // });
    if (this.name == null) {
      this.name = "未登录";
      // this.$router.push("/login");
    } else {
      this.name = this.name.replace(/^"|"$/g, '');
    }
    this.findAllData();//获取首页寄件派件数据
    this.getMember();//获取会员数据
    this.getNewNum();//获取新开柜机数量
    this.getMapData();//获取地图数据
  },
  mounted() {
    this.getNowTime(); // 进入页面调用该方法获取当前时间
    this.clearTimer(); // 清除之前定时器
    this.myTimeDisplay = setInterval(() => {
      this.getNowTime(); // 每秒更新一次时间
    }, 1000);

    setInterval(() => {
      this.getNewNum();
    }, 60000);//每一分钟更新一次数据

  },
  beforeDestroy() {
    this.clearTimer(); // 在组件销毁前清除定时器
  },
  methods: {
    // 渲染地图数据柱状图
    renderMapDataChart() {
      if (this.mapDataChart) {
        this.mapDataChart.destroy(); // 销毁旧图表
      }

      // 检查 mapData 是否有数据
      if (this.mapData.length === 0 ) {
        console.error("没有可用的数据来渲染图表");
        return; // 数据为空时退出
      }

      // 提取城市和数量
      const labels = this.mapData.map(item => item.name);
      const values = this.mapData.map(item => item.value);

      const backgroundColors = values.map(num => {
        if (num > 20) {
          return 'rgba(253, 165, 11, 0.8)';
        } else if (num <= 20 && num > 10) {
          return 'rgba(151, 206, 104, 0.8)';
        } else if (num <= 10 && num > 5){
          return 'rgba(107, 203, 202, 0.8)';
        } else {
          return 'rgba(163, 228, 227, 0.8)';
        }
      });

      // 获取 ID 为 'myBarChart' 的 <canvas> 元素，并获取其 2D 渲染上下文
      const ctx = document.getElementById('mapDataChart').getContext('2d');

      // 绘制横向柱状图
      this.chart = new Chart(ctx, {
        type: 'bar', // 更改类型为 'bar'
        data: {
          labels: labels,
          datasets: [
            {
              label: '数量',
              data: values,
              backgroundColor: backgroundColors, // 背景颜色
            }
          ]
        },
        options: {
          indexAxis: 'y', // 横向柱状图
          scales: {
            x: {
              beginAtZero: true,
              title: {
                display: true,
                text: '数量'
              }
            },
            y: {
              title: {
                display: true,
                text: '城市'
              }
            }
          },
          responsive: true,
          plugins: {
            legend: {
              display: true,
              position: 'top',
            },
            title: {
              display: true,
              text: '城市数量柱状图'
            }
          },
          elements: {
            bar: {
              // 设置固定的柱子宽度比例（范围 0 到 1）
              barPercentage: 0.5, // 柱子的宽度占类别宽度的比例
              categoryPercentage: 1.0 // 每个分类的宽度比例
            }
          }
        }
      });
    },
    // 获取地图数据
    getMapData() {
      getMapChart().then(res => {
        this.mapData = res.data;
        console.log(this.mapData)
        this.renderMapDataChart();
      }).catch(err => {
        console.error("获取会员数据失败", err);
      })
    },
    // 渲染新增会员环状图
    renderAddMemberChart() {
      if (this.addMemberChart) {
        this.addMemberChart.destroy(); // 销毁旧图表
      }

      const ctx = document.getElementById('myDoughnutAddChart').getContext('2d');

      this.addMemberChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: ['新增会员', '新增快递员'],
          datasets: [{
            data: [this.addMember.vipNum, this.addMember.courierNum],
            backgroundColor: ['#4095e5', '#ffbf6b'],
            hoverOffset: 4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {}
          },
          cutout: '60%', // 设置环的厚度
        },
      })
    },
    // 渲染会员环状图
    renderMemberChart() {
      if (this.memberChart) {
        this.memberChart.destroy(); // 销毁旧图表
      }

      const ctx = document.getElementById('myDoughnutChart').getContext('2d');

      this.memberChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: ['会员', '快递员'],
          datasets: [{
            data: [this.member.vipNum, this.member.courierNum],
            backgroundColor: ['#59d4d4', '#5087ec'],
            hoverOffset: 4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {}
          },
          cutout: '60%', // 设置环的厚度
        },
      });
    },
    // 获取会员数据
    getMember() {
      Promise.all([
        axios.get('http://localhost:10020/expressList/getMember'),
        axios.get('http://localhost:10020/expressList/getNewAddNum')
      ]).then(responses => {
        this.member = responses[0].data;
        this.addMember = responses[1].data;

        this.renderMemberChart(); // 数据获取成功后渲染图表
        this.renderAddMemberChart();
      }).catch(error => {
        console.error("获取会员数据失败", error);
      })
    },
    // 获取新开柜机数量
    getNewNum() {
      getNewOpenNum().then(res => {
        this.newNumber = res.data;
        console.log(this.newNumber);
      })
    },
    //渲染折线图
    renderChart() {
      if (this.chart) {
        this.chart.destroy(); // 销毁旧图表
      }

      // 检查 deliveryLineChart 是否有数据
      if (this.deliveryLineChart.length === 0) {
        console.error("没有可用的数据来渲染图表");
        return; // 数据为空时退出
      }

      // 获取所有的月份
      const allMonths = new Set([
        ...this.deliveryLineChart.map(item => item.month),
        ...this.sendLineChart.map(item => item.month)
      ]);

      const labels = Array.from(allMonths).sort(); // 将 Set 转换为数组并排序

      // 创建对应月份的寄件量和派件量数组
      const deliveryValues = labels.map(month => {
        const entry = this.deliveryLineChart.find(item => item.month === month);
        return entry ? parseInt(entry.num) : 0; // 如果没有数据，返回0
      });

      const sendValues = labels.map(month => {
        const entry = this.sendLineChart.find(item => item.month === month);
        return entry ? parseInt(entry.num) : 0; // 如果没有数据，返回0
      });

      // 获取 ID 为 'myLineChart' 的 <canvas> 元素，并获取其 2D 渲染上下文
      const ctx = document.getElementById('myLineChart').getContext('2d');

      // 绘制折线图
      this.chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [
            {
              label: '派件量',
              data: deliveryValues,
              backgroundColor: 'rgba(64, 149, 229, 0.4)', // 背景颜色
              borderColor: 'rgba(64, 149, 229, 1)', // 边框颜色
              borderWidth: 1,
              fill: true
            },
            {
              label: '寄件量',
              data: sendValues,
              backgroundColor: 'rgba(129, 179, 55, 0.4)', // 背景颜色
              borderColor: 'rgba(129, 179, 55, 1)', // 边框颜色
              borderWidth: 1,
              fill: true
            }
          ]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true,
              title: {
                display: true,
                text: '数量'
              }
            },
            x: {
              title: {
                display: true,
                text: '月份'
              }
            }
          },
          responsive: true,
          plugins: {
            legend: {
              display: true,
              position: 'top',
            },
            title: {
              display: true,
              text: '数据折线图'
            }
          }
        }
      });
    },
    // 获取首页寄件派件数据
    findAllData() {
      axios.get(`http://localhost:10061/package/sendCount`).then(res => {
        this.sendDay = res.data;
      })
      axios.get(`http://localhost:10061/package/deliveryCount`).then(res => {
        this.deliveryDay = res.data;
      })

      Promise.all([
        axios.get(`http://localhost:10061/package/findLineChartSend`),
        axios.get(`http://localhost:10061/package/findLineChartDelivery`)
      ]).then(([sendRes, deliveryRes]) => {
        this.sendLineChart = sendRes.data;
        this.deliveryLineChart = deliveryRes.data;
        this.renderChart(); // 数据加载完成后渲染图表
      }).catch(error => {
        console.error('获取折线图数据失败:', error);
      });
    },
    // 获取当前时间
    getNowTime() {
      // 使用 moment.js 更新格式化日期
      this.formattedDate = moment().format('YYYY-MM-DD');

      // 获取当前时间
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      // 更新星期几
      const daysOfWeek = ["日", "一", "二", "三", "四", "五", "六"];
      this.currentDay = `星期${daysOfWeek[now.getDay()]}`; // 直接使用 getDay()

      // 更新当前时间
      this.currentTime = `${hours}:${minutes}:${seconds}`;
    },
    // 清除定时器
    clearTimer() {
      if (this.myTimeDisplay) {
        clearInterval(this.myTimeDisplay);
      }
    },
    handleSelect(key) {
      console.log(key);
    },
    login() {
      this.$router.push({path: "/login"})
    },
    tiaozhuan() {
      this.$router.push({
        path: '/zhanghuPage'
      })
    },
    expressList() {
      this.$router.push(
          {path: "/expressList"}
      )
    },
    xitong() {
      this.$router.push(
          {path: "/OutSystems"}
      )
    },
    baoguo() {
      this.$router.push(
          {path: "/OutPackage"}
      )
    },
    notice() {
      this.$router.push(
          {path: "/HomePage"}
      )
    },
    ba() {
      this.$router.push(
          {path: "/dropdown"}
      )
    },
    //跳转其他页面
    other() {
      this.$router.push(
          {path: "/otherView"}
      )
    },
    goToMachine() {
      this.$router.push(
          {path: "/machineHome"}
      )
    },
    handleCommand(command) {
      if (command == 'a') {
        this.toAccount();
      } else if (command == 'b') {
        this.toAccount();
      } else if (command == 'c') {
        this.delAccount();
      }
    },
    toAccount() {
      this.$router.push(
          {path: "/accountManagement"}
      )
    },
    delAccount() {
      sessionStorage.clear();
      Message.success('退出成功');
      location.replace("/");
    },
    openMap() {
      this.$router.push(
          {path: "/mapChart"}
      )
    }
  }
};
</script>

<style lang="less">
#app {
  margin-top: 0;
}

.home-container {
  height: 100%;
}

.el-header {
  background-color: #545c64;
  display: flex; //设置显示为flex布局
  justify-content: space-between; //设置为flex左右布局
  padding-left: 0; //左内边距为0（Logo贴左边）
  align-items: center; //元素上下居中（防止右边按钮贴上下边）
  color: #fff;
  font-size: 18px;

  > div {
    //内嵌的div样式
    display: flex;
    align-items: center; //Logo和文字上下居中
    #fontLogo {
      width: 200px;
      margin-left: 10px; //文字左侧设置间距，防止与Logo紧贴
    }

    #fontName {
      display: block;
      width: 120px;
      margin-right: 10px;
      color: #f8f8f8;
    }
  }
}

#indexMenu {
  width: 100%;
}

.el-menu {
  background-color: #545c64;
}

.el-aside {
  background-color: #545c64;
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}

.el-main {
  background-color: #eaedf1;
  height: 100%;
}

#indexOne {
  height: 100px;
  border-radius: 8px;
  text-align: left;
  padding-left: 20px;
  padding-top: 20px;
}

#indexOneFont {
  color: #f8f8f8;
  font-size: 14px;
}

#indexOneNumber {
  display: inline-block;
  color: #f8f8f8;
  font-size: 30px;
  margin-top: 10px;
}

#indexTwoLeft {
  height: 350px;
  background-color: #f8f8f8;
  border-radius: 8px;
  margin-right: 10px;
  text-align: left;
  padding: 10px;
}

#indexTwoRight {
  height: 300px;
  background-color: #f8f8f8;
  border-radius: 8px;
  margin-left: 10px;
  padding: 10px;
  text-align: left;
}

#indexTwoRightBottom {
  text-align: center;
  margin-left: 40px;
  margin-top: 30px;
  width: 200px;
  height: 280px;
}

#indexTwoRightYuan {
  border: 2px solid rgb(64, 149, 229);
  border-radius: 50%;
  width: 200px;
  height: 200px;
  text-align: center; /* 文本居中 */
}

#indexThreeLeft {
  background-color: #f8f8f8;
  border-radius: 8px 0 0 8px;
  height: 350px;
  text-align: left;
  padding: 10px;

}

#indexThreeRight {
  background-color: #f8f8f8;
  border-radius: 0 8px 8px 0;
  height: 350px;
  text-align: left;
  padding: 10px;
}

#indexFourLeft {
  background-color: #f8f8f8;
  border-radius: 8px 0 0 8px;
  height: 600px;
  text-align: left;
  padding: 10px;

}

#mapDiv {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 10px;
}

#indexFourRight {
  background-color: #f8f8f8;
  border-radius: 0 8px 8px 0;
  height: 570px;
  text-align: left;
  padding: 40px 10px 10px;
}
#mapDataChart{
  width: 200px;
  height: 200px;
}
</style>
